<template>
  <div>
    <customDialog
      :title="`${'收费设置-' + title}`"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmSet(ruleFormRef)"
      :showCancel="false"
      :confirmText="'保存设置'"
      width="1100"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-width="110px"
          class="form_box"
        >
          <el-row>
            <el-col :span="10">
              <el-form-item label="每集价格" prop="unblockCoinAmount">
                <el-input
                  v-model.number="formData.unblockCoinAmount"
                  placeholder="请输入每集价格"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <span style="vertical-align: sub">&nbsp;(单位：金币)</span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item
                label="付费卡点"
                prop="chargeEpisodeNo"
                class="item_episodeNo"
                style="margin-left: -18px"
              >
                <el-tooltip
                  effect="dark"
                  content="新进用户立即生效，已进用户需等一段时间"
                  placement="top"
                >
                  <el-icon
                    class="tooltip_color"
                    style="
                      margin: 0 10px 0 -10px;
                      font-size: 18px;
                      cursor: pointer;
                    "
                  >
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                <el-input
                  v-model.number="formData.chargeEpisodeNo"
                  placeholder="请输入付费卡点"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <span style="vertical-align: sub">
                &nbsp;({{ ` 从第${formData.chargeEpisodeNo}集开始收费` }})
              </span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="卡点预览秒数" prop="previewSeconds">
                <el-input-number v-model="formData.previewSeconds" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item label="充值模板" prop="isDiffRecharge">
                <el-select
                  v-model="formData.isDiffRecharge"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, i) in tempalteOptions"
                    :key="i"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="">
                <!-- 区分首充 -->
                <div class="diff_box" v-if="formData.isDiffRecharge">
                  <!-- 首充 -->
                  <div>
                    <el-form-item
                      label="首充用户"
                      class="common_select"
                      label-position="left"
                    >
                      <el-select
                        v-model="formData.firstPayTplId"
                        placeholder="请选择充值模板"
                        style="width: 100%"
                        @change="firstTemplate"
                      >
                        <el-option
                          v-for="(item, i) in optionsTemplate"
                          :key="i"
                          :label="item.text"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                    <defaultTemlate ref="baseTemplateRef1" />
                  </div>
                  <!-- 非首充 -->
                  <div style="margin-left: 30px">
                    <el-form-item
                      label="非首充用户"
                      class="common_select"
                      label-position="left"
                    >
                      <el-select
                        v-model="formData.payTplId"
                        placeholder="请选择充值模板"
                        style="width: 100%"
                        @change="changeTemplate"
                      >
                        <el-option
                          v-for="(item, i) in optionsTemplate"
                          :key="i"
                          :label="item.text"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                    <defaultTemlate ref="baseTemplateRef" />
                  </div>
                </div>
                <!-- 不区分首充 -->
                <div v-if="!formData.isDiffRecharge">
                  <el-form-item class="common_select">
                    <el-select
                      v-model="formData.payTplId"
                      placeholder="请选择充值模板"
                      style="width: 100%"
                      @change="changeTemplate"
                    >
                      <el-option
                        v-for="(item, i) in optionsTemplate"
                        :key="i"
                        :label="item.text"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <defaultTemlate ref="baseTemplateRef" />
                </div>
                <!-- 默认 -->
                <!-- <div v-if="!formData.isDiffRecharge">
                  <defaultTemlate ref="baseTemplateRef" />
                </div> -->
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item label="">
                <div>
                  <el-button type="primary" @click="confirmSet(ruleFormRef)">
                    保存设置
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customDialog from "@/components/CustomDialog/index.vue";
import defaultTemlate from "@/components/DefaultRechargeTemlate/defaultTemlate.vue";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import type { FormInstance } from "element-plus";
import { QuestionFilled } from "@element-plus/icons-vue";
import {
  listForSelector,
  getById,
} from "@/api/globalManage/defaultTemplate/index";
import { getPayment, updatePayment } from "@/api/promotionLink/index";
import { cloneDeep, debounce } from "lodash-es";

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const form = {
  id: 0,
  unblockCoinAmount: undefined, // 每集价格
  chargeEpisodeNo: undefined, // 付费集数
  isDiffRecharge: false, // 是否具分首充
  firstPayTplId: undefined, // 首充充值模板库ID
  payTplId: undefined, // 充值模板库 Id
  previewSeconds: 0, // 预览时长
  firstPayTpl: {
    items: [],
  }, //  首充区分
  payTpl: {
    items: [],
  }, //  非首冲
};
const formData = ref(Object.assign({}, form));

const title = ref<string>("");
const appId = ref();
const optionsTemplate = ref<Array<any>>([]);
const episodeNumTotal = ref();

const tempalteOptions = ref([
  { label: "区分首充", value: true },
  { label: "不区分首充", value: false },
]);

// 付费卡点 / 每集价格 规则
const episodeNoRules = (rule: any, value: any, callback: any) => {
  let reg = /^[1-9]\d*$/; // 大于0的整数
  if (rule.field === "chargeEpisodeNo") {
    if (!+value || +value < 0) {
      return callback(new Error("请填写大于0的整数"));
    } else if (!reg.test(value) || +value > episodeNumTotal.value) {
      return callback(
        new Error(`请输入剧集${episodeNumTotal.value}之内的集数`)
      );
    } else {
      callback();
    }
  } else if (rule.field === "unblockCoinAmount") {
    if (!+value || !reg.test(value)) {
      return callback(new Error(`请输入大于0的整数`));
    } else if (+value < 10) {
      return callback(new Error("每集需要消耗的追剧币不能低10"));
    } else if (+value > 1000) {
      return callback(new Error(`每集需要消耗的追剧币不能高于1000`));
    } else {
      callback();
    }
  }
};

const rules = reactive({
  unblockCoinAmount: [
    { required: true, validator: episodeNoRules, trigger: "blur" },
  ],
  chargeEpisodeNo: [
    { required: true, validator: episodeNoRules, trigger: "blur" },
  ],
  isDiffRecharge: [
    { required: true, message: "请选择模板", trigger: "change" },
  ],
});

// 切换模板
const baseTemplateRef = ref();
// 非首充用户
const changeTemplate = (val: number | string) => {
  if (!baseTemplateRef.value) return;
  getById(val).then((res: Record<string, any>) => {
    nextTick(() => {
      baseTemplateRef.value.relationDtoList = cloneDeep(res?.items);
    });
  });
};

// 首充用户
const baseTemplateRef1 = ref();
const firstTemplate = (val: number | string) => {
  if (!baseTemplateRef1.value) return;
  getById(val).then((res: Record<string, any>) => {
    nextTick(() => {
      baseTemplateRef1.value.relationDtoList = cloneDeep(res?.items);
    });
  });
};

// 获取下拉充值模板list
const getTemplateList = () => {
  listForSelector({}).then((res: Record<string, any>) => {
    optionsTemplate.value = cloneDeep(res) || [];
  });
};

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  dialogVisible.value = false;
  formEl?.resetFields();
};

// 成功
const emit = defineEmits(["success"]);
const confirmSet = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let firstTemp = baseTemplateRef1.value?.relationDtoList || [];
      let Temp = baseTemplateRef.value?.relationDtoList || [];
      if (!formData.value.isDiffRecharge && !Temp.length) {
        return ElMessage.warning("抱歉，充值模板不能为空");
      } else if (
        formData.value.isDiffRecharge &&
        (!Temp.length || !firstTemp.length)
      ) {
        return ElMessage.warning("抱歉，首充和非首充模板都不能为空");
      }

      // 区分首充，首充模板调用
      if (formData.value.isDiffRecharge) {
        let temp = await confirmTemp(1);
        formData.value.firstPayTpl = temp;
      }
      let temp1 = await confirmTemp(0);
      formData.value.payTpl = temp1; // 区分首充-非首充模板、不区分首充、默认 调用，

      formData.value.previewSeconds = formData.value?.previewSeconds || 0;
      updatePayment(formData.value).then(() => {
        ElMessage.success(`保存成功`);
        emit("success");
        dialogVisible.value = false;
      });
    }
  });
}, 200);

// 修改充值模板
const confirmTemp = (val = 0) => {
  let items = val
    ? baseTemplateRef1.value.relationDtoList
    : baseTemplateRef.value.relationDtoList; // 区分首充-判断是否首冲模板
  let id = val ? formData.value.firstPayTplId : formData.value.payTplId; // 区分首充-判断是否首冲模板id
  let params = {
    id: id,
    name:
      optionsTemplate.value.find((x: Record<string, any>) => x.value === id)
        ?.text || "",
    items: items,
  };
  return params;
};

// 获取收费设置详情
const getPaymentData = (id: number) => {
  getPayment(id).then((res: Record<string, any>) => {
    if (res?.payTpl?.items.length) {
      if (!baseTemplateRef.value) return;
      baseTemplateRef.value.relationDtoList = cloneDeep(res?.payTpl?.items);
    }
    if (res?.firstPayTpl?.items.length) {
      if (!baseTemplateRef1.value) return;
      baseTemplateRef1.value.relationDtoList = cloneDeep(
        res?.firstPayTpl?.items
      );
    }
  });
};

// 父级电子显示dialog
const showDialog = (val: Record<string, any>) => {
  // console.log("收费设置弹窗--formData.value----", val);
  title.value = val?.linkName;
  episodeNumTotal.value = val?.episodeNum || undefined;
  appId.value = val?.appId;
  dialogVisible.value = true;
  formData.value = cloneDeep(val);

  formData.value.firstPayTplId = undefined;
  formData.value.payTplId = undefined;
  getTemplateList();
  getPaymentData(val?.id);
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.form_box {
  // :deep(.el-input__inner) {
  // width: 120px;
  // }

  .diff_box {
    display: flex;
    // flex-direction: column;
    padding: 18px;
    // background-color: #eee;
    background-color: rgb(238 238 238 / 50%);
    border-radius: 10px;
  }

  .common_select {
    margin-bottom: 10px;
  }

  .item_episodeNo {
    :deep(.el-form-item__content) {
      flex-wrap: nowrap;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;
  }
}
</style>
